import { create } from "zustand";
import { persist, createJSONStorage } from "zustand/middleware";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { UserProgress, UserAnswer, SimulationResult } from "@/types/question";

interface UserState extends UserProgress {
  addAnswer: (answer: UserAnswer) => void;
  addSimulation: (simulation: SimulationResult) => void;
  toggleBookmark: (questionId: string) => void;
  updateStreak: () => void;
  resetProgress: () => void;
}

const initialState: UserProgress = {
  answeredQuestions: {},
  bookmarkedQuestions: [],
  simulations: [],
  streakDays: 0,
};

export const useUserStore = create<UserState>()(
  persist(
    (set, get) => ({
      ...initialState,
      addAnswer: (answer: UserAnswer) =>
        set((state) => ({
          answeredQuestions: {
            ...state.answeredQuestions,
            [answer.questionId]: answer,
          },
        })),
      addSimulation: (simulation: SimulationResult) =>
        set((state) => ({
          simulations: [simulation, ...state.simulations],
        })),
      toggleBookmark: (questionId: string) =>
        set((state) => {
          const isBookmarked = state.bookmarkedQuestions.includes(questionId);
          return {
            bookmarkedQuestions: isBookmarked
              ? state.bookmarkedQuestions.filter((id) => id !== questionId)
              : [...state.bookmarkedQuestions, questionId],
          };
        }),
      updateStreak: () =>
        set((state) => {
          const today = new Date().setHours(0, 0, 0, 0);
          const lastPractice = state.lastPracticeDate || 0;
          const yesterday = today - 86400000; // 24 hours in milliseconds
          let newStreakDays = state.streakDays;
          // If last practice was yesterday, increment streak
          if (lastPractice === yesterday) {
            newStreakDays += 1;
          }
          // If last practice was before yesterday, reset streak
          else if (lastPractice < yesterday) {
            newStreakDays = 1;
          }
          // If already practiced today, keep streak the same
          return {
            streakDays: newStreakDays,
            lastPracticeDate: today,
          };
        }),
      resetProgress: () => set(initialState),
    }),
    {
      name: "interview-prep-storage",
      storage: createJSONStorage(() => AsyncStorage),
    }
  )
);
